import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { RequestProductDetailById } from '@/api/product'
import type { Ref } from 'vue'
import type { IProduct } from '@/types/Types'
import { useCartStore } from '@/stores/cart'
import { Toast } from 'vant'
import router from "@/router/index";
import { Dialog } from 'vant';

export const useProduct = () => {
	const route = useRoute()

	let product: Ref<IProduct> = ref({ id: 0, shop: '', product: '', picture: '', price: 0 })

	const onClickLeft = () => {
		history.back()
	}

	/**
	 * 商品详情
	 */
	const getProductDetail = async (id: number) => {
		let data = await RequestProductDetailById(id)
		let { resultCode, resultInfo } = data
		if (resultCode == 1) {
			product.value = resultInfo
		}
	}

	onMounted(() => {
		let id: number = Number(route.params.id) //商品id
		getProductDetail(id)
	})

	const addCart = () => {
		let token = localStorage.getItem('TOKEN')

		
        if (token) {
        // 根据当前要添加商品，判断购物车数组中是否存在，
		// 如果商品存在数量加一
		const cartStore = useCartStore()
		let cartList = cartStore.cartList
		let oldProduct = cartList.find((item: IProduct) => item.id == product.value.id)
		if (oldProduct) {
			// 数量加一
			oldProduct.num++
		} else {
			//添加新商品
			cartStore.addProduct({
				id: product.value.id,
				name: product.value.product,
				url: product.value.picture,
				price: product.value.price,
				num: 1,
				state: false,
			})
		}
		Toast.success('添加购物车成功')
        } else {

            Dialog.confirm({
                title: '提示',
                message:
                    '亲，您现在还没有登录，赶快去登录吧',
            })
                .then(() => {
                    router.push({path:'/login'})
                    
                    // return { path: '/login' } //重定向到/路由登录界面
                })
                // .catch(() => {
                //     //   on cancel
                //     console.log('error')
				// 	router.push({path:'/detail'})
                // });

        }


	
	}

	return {
		onClickLeft,
		product,
        addCart
	}
}

/**
 * 添加购物车
 */
// export const useCartDetail = ()=>{

// }
